package com.zhangxin.aiInterview.manager.python_api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.utils.AudioEmotionsSequenceManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.zhangxin.aiInterview.constant.PythonConstant.python_base_url_http;

/**
 * python接口调用（http请求）
 */
@Service
@Slf4j
public class PythonApi {
    @Resource
    private AudioEmotionsSequenceManager audioEmotionsSequenceManager;

    /**
     * 获取多条面试题的技术栈列表
     *
     * @param questions 面试题列表
     * @return 每道题对应的技术栈列表，Map中key为问题，value为该问题提取的技术栈
     */
    public Map<String, List<String>> getTechStacks(List<String> questions) {
        Map<String, List<String>> resultMap = new HashMap<>();

        // 1. 直接将 List<String> 序列化为 JSON 数组字符串
        String requestBody = JSONUtil.toJsonStr(questions);
        // 2. 发送请求
        HttpResponse response = HttpRequest.post(python_base_url_http + "/extract-tech-stack")
                .body(requestBody) // <--- 发送正确的 JSON 数组字符串
                .contentType("application/json")
                .timeout(5000)
                .execute();

        // 3. 处理响应 (这部分无需修改)
        if (response.isOk()) {
            JSONObject json = JSONUtil.parseObj(response.body());
            JSONArray results = json.getJSONArray("results");

            for (Object obj : results) {
                JSONObject item = (JSONObject) obj;
                String question = item.getStr("question");
                JSONArray techStackArray = item.getJSONArray("tech_stacks");

                List<String> techStackList = new ArrayList<>();
                techStackArray.forEach(stack -> techStackList.add(stack.toString()));
                resultMap.put(question, techStackList);
            }
        }

        return resultMap;
    }



    /**
     * 面试多模态评分（接收 Python 接口返回的 float 分数，如 47.17）
     * @param interviewContentObj 面试多模态数据
     * @param userId 用户ID
     * @param url Python 多模态评分接口地址
     */
    public Double interviewMultimodalScoring(Object interviewContentObj, Long userId, String url) {
        // 获取音频情感序列（从全局管理器获取）
        List<String> emotionSequences = audioEmotionsSequenceManager.getEmotionSequences(userId);

        // 清除用户的音频情感序列（一次性使用后清除）
        audioEmotionsSequenceManager.clearEmotionSequences(userId);

        try {
            Map<String, Object> payload = new HashMap<>();
            // 需要处理的字段列表（移除了audioEmotion）
            List<String> requiredFields = Arrays.asList(
                    "speechRate", "facialActions",
                    "bodyMovements", "microExpression", "stress"
            );

            // 用反射处理其他字段
            for (String fieldName : requiredFields) {
                Field field = ReflectUtil.getField(interviewContentObj.getClass(), fieldName);
                if (field != null) {
                    Object rawValue = ReflectUtil.getFieldValue(interviewContentObj, field);
                    if (rawValue instanceof String && StrUtil.isNotBlank((String) rawValue)) {
                        payload.put(fieldName, JSONUtil.parseArray((String) rawValue));
                    } else {
                        payload.put(fieldName, new JSONArray()); // 空数组兜底
                    }
                }
            }

            // 特殊处理音频情感字段 - 直接序列化整个列表
            payload.put("audioEmotion", JSONUtil.parseArray(emotionSequences));

            // 发送请求
            String json = JSONUtil.toJsonStr(payload);
            HttpResponse response = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .body(json)
                    .timeout(5000)
                    .execute();

            String responseBody = response.body();
            Double score = JSONUtil.parseObj(responseBody).getDouble("score");

            if (score < 0) System.err.println("返回分数格式异常！");
            return score;

        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "调用多模态打分接口失败：" + e.getMessage());
        }
    }



    /**
     * 使用Hutool调用FastAPI情绪分析接口
     *
     * @param localAudioUrl 本地音频文件路径（如：D:/interview.wav）
     * @return 情绪标签字符串
     * @throws Exception 调用失败时抛出异常
     */
    public String analyzeEmotion(String localAudioUrl) {
        // 1. 构建完整请求URL（自动处理URL编码）
        String encodePath = URLEncoder.DEFAULT.encode(localAudioUrl, StandardCharsets.UTF_8);

        String api = python_base_url_http + "/analyze-emotion?path=" + encodePath;

        // 2. 发送GET请求
        // 发送HTTP请求并获取完整响应对象
        HttpResponse response = HttpUtil.createGet(api).execute();
        if (!response.isOk()) {
            return "没有提取到有效音频，情绪检测失效";
        }

        String emotion = response.body();
        System.out.println(emotion);
        return emotion;
    }

    /**
     * 调用python接口谎言检测
     *
     * @param localAudioUrl
     * @return
     */
    public String lieCheck(String localAudioUrl) {
        String encodePath = URLEncoder.DEFAULT.encode(localAudioUrl, StandardCharsets.UTF_8);
        String api = python_base_url_http + "/stress/detection?path=" + encodePath;

        try {
            String response = HttpUtil.get(api);
            JSONObject json = JSONUtil.parseObj(response);

            if (json.containsKey("detail")) {
                System.out.println("接口返回错误: " + json.getStr("detail"));
                return "";
            } else {
                System.out.println("=== 分析结果 ===");
                System.out.println("f0_var           : " + json.getDouble("f0_var"));
                System.out.println("spectral_flux    : " + json.getDouble("spectral_flux"));
                System.out.println("energy_entropy   : " + json.getDouble("energy_entropy"));
                System.out.println("silence_ratio    : " + json.getDouble("silence_ratio"));
                System.out.println("energy_variability    : " + json.getDouble("energy_variability"));
                System.out.println("speech_duration    : " + json.getDouble("speech_duration"));
                System.out.println("jitter    : " + json.getDouble("jitter"));
                System.out.println("shimmer    : " + json.getDouble("shimmer"));
                System.out.println("mfcc1_var    : " + json.getDouble("mfcc1_var"));
                System.out.println("mean_f0    : " + json.getDouble("mean_f0"));
                System.out.println("stress                : " + json.getDouble("stress"));
                return json.getDouble("stress").toString();
            }
        } catch (Exception e) {
            log.error("谎言识别接口调用异常: ", e);
        }
        return "";
    }
}
